from sqlalchemy.orm import Session
from app.models.users import User
from app.schemas.users import UserCreate, UpdateUser
from app.utils.security import get_hash_password


def get_user_by_id(db: Session, user_id: int):
    """通过ID获取单个用户"""
    return db.query(User).filter(User.id == user_id).first()


def get_user_by_username(db: Session, username: str):
    """通过用户名获取用户"""
    return db.query(User).filter(User.username == username).first()


def get_user_by_email(db: Session, email: str):
    """通过email获取用户"""
    return db.query(User).filter(User.email == email).first()


def get_users(db: Session, skip: int = 0, limit: int = 100):
    """获取用户列表"""
    return db.query(User).offset(skip).limit(limit).all()


def create_user(db: Session, user: UserCreate):
    """创建新用户"""
    hashed_password = get_hash_password(user.password)
    db_user = User(
        username=user.username, email=user.email, hashed_password=hashed_password
    )
    db.add(db_user)
    db.commit()
    db.refresh(db_user)
    return db_user


def update_user(db: Session, user_id: int, user_data: UpdateUser):
    """
    更新用户信息
    user_id: 需要更新的用户id
    user_data: UpdateUser, 如: username='' email='' password='' is_active=False is_superuser=False
    """
    db_user = db.query(User).filter(User.id == user_id).first()
    if not db_user:
        return None

    # 删除数据字典中字符串为空的k-v值
    user_data_dict_not_null = {k: v for k, v in dict(user_data).items() if v != ""}
    print("update:", user_data_dict_not_null)
    if user_data_dict_not_null:
        # 判断是否需要更新密码
        if "password" in user_data_dict_not_null:
            # 将明文密码进行hash存储
            hash_password = get_hash_password(user_data_dict_not_null.get("password"))
            # 删除字典中的hassword字段
            user_data_dict_not_null.pop("password")
            # 添加hassed_password键值对
            user_data_dict_not_null["hashed_password"] = hash_password

        # 用户名重复校验
        if "username" in user_data_dict_not_null:
            if get_user_by_username(db, user_data_dict_not_null["username"]):
                return {"msg": "用户名已经存在!"}

        # email重复校验
        if "email" in user_data_dict_not_null:
            if get_user_by_email(db, user_data_dict_not_null["email"]):
                return {"msg": "邮箱已经存在!"}

        # 循环修改数据
        for k, v in user_data_dict_not_null.items():
            setattr(db_user, k, v)

        db.commit()
        db.refresh(db_user)
        return db_user


def delete_user(db: Session, user_id: int):
    """删除用户"""
    db_user = db.query(User).filter(User.id == user_id).first()
    if not db_user:
        return False

    db.delete(db_user)
    db.commit()
    return True
